<template>
  <div ref="appRef" class="App" v-resize="onResize">
    <canvas ref="canvasRef" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import Game from "./game";

const appRef = ref<HTMLDivElement>();
const canvasRef = ref<HTMLCanvasElement>();

function onResize(event: Event) {
  if (canvasRef.value && appRef.value) {
    canvasRef.value.width = appRef.value.offsetWidth;
    canvasRef.value.height = appRef.value.offsetHeight;
  }
}

function isMobile() {
  if (window.navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)) {
    return true; // 移动端
  } else {
    return false; // PC端
  }
}

onMounted(() => {
  if (canvasRef.value) {
    const game = new Game(canvasRef.value);
    game.loadData(async () => {
      const response = await fetch("/data.json");
      const data = response.json();
      return data;
    }).then(() => {
      game.play();
    });

    window.addEventListener("keydown", () => {
      game.touch();
    });

    window.addEventListener(isMobile() ?  "touchstart" : "click", () => {
      game.touch();
    });
  }
});


</script>

<style scoped>
.App {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>
